package com.henu.tanhang.poisearch;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.henu.R;
import com.henu.tanhang.CheakAll;
import com.henu.tanhang.overlay.PoiOverlay;

/**
 * Created by th on 2017/5/18.
 */

public class PoiSearchManager {

    private EditText searchlist;
    private BaiduMap baiduMap;
    private PoiSearch mPoiSearch;
    private SuggestionSearch mSuggestionSearch = null;
    private MyLocationData locationData;
    private ImageView iv_pop;
    private int radius;
    private TextView tv_popname;
    private TextView tv_popnum;
    private TextView tv_popaddress;
    private TextView tv_popkm;
    Context context;

    public PoiSearchManager(Context context) {
        this.context = context;
    }

    public interface  MyListerner{
        public void callBack(PoiInfo info);
    }


    public void init(final MyListerner listerner) {
        // 初始化搜索模块，注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
            /**
             * 获取POI搜索结果，包括searchInCity，searchNearby，searchInBound返回的搜索结果
             * 这里只有搜索附近的
             * @param result
             */
            @Override
            public void onGetPoiResult(PoiResult result) {
                try {
                    if (locationData == null) {
                        Toast.makeText(context, "请先定位！", Toast.LENGTH_LONG).show();
                    } else {
                        LatLng center = new LatLng(locationData.latitude, locationData.longitude);
                        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
                            Toast.makeText(context, "未找到结果", Toast.LENGTH_LONG)
                                    .show();
                            return;
                        }
                        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
                            baiduMap.clear();
                            PoiOverlay overlay = new MyPoiOverlay(baiduMap);
                            baiduMap.setOnMarkerClickListener(overlay);
                            overlay.setData(result);
                            overlay.addToMap();
                            overlay.zoomToSpan();
                            showNearbyArea(center, radius);
                            for(PoiInfo info:result.getAllPoi()){
                                listerner.callBack(info);
                            }
                            return;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            /**
             * 获取POI详情搜索结果，得到searchPoiDetail返回的搜索结果
             * @param result
             */
            @Override
            public void onGetPoiDetailResult(PoiDetailResult result) {
                Log.d("TAG","detail");
                if (result.error != SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(context, "抱歉，未找到结果", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    initPop();
                    if (result.getType().equals("hotel")) {
                        iv_pop.setBackgroundResource(R.drawable.hotel);
                    } else if (result.getType().equals("cater")) {
                        iv_pop.setBackgroundResource(R.drawable.restaurant);
                    } else if (result.getType().equals("life")) {
                        iv_pop.setBackgroundResource(R.drawable.life);
                    } else {
                        iv_pop.setBackgroundResource(R.drawable.life);
                    }
                    double la = result.getLocation().latitude;
                    double lo = result.getLocation().longitude;
                    int dis =(int)Distance(locationData.latitude,locationData.longitude,la,lo);
                    tv_popkm.setText("距离"+dis+"m");
                    tv_popname.setText(result.getName());
                    tv_popaddress.setText(result.getAddress());
                    tv_popnum.setText(result.getTelephone());
                }

            }

            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

            }
        });

        // 初始化建议搜索模块，注册建议搜索事件监听
        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(new OnGetSuggestionResultListener() {
            @Override
            public void onGetSuggestionResult(SuggestionResult suggestionResult) {

            }
        });
    }

    public boolean requestSuggest(String params) {
        return mSuggestionSearch
                .requestSuggestion((new SuggestionSearchOption())
                        .keyword(params).city("开封"));
    }

    public boolean search(PoiNearbySearchOption option, BaiduMap baiduMap, MyLocationData locationData,int radius) {
        this.baiduMap = baiduMap;
        this.radius = radius;
        this.locationData = locationData;
        return mPoiSearch.searchNearby(option);
    }

    private class MyPoiOverlay extends PoiOverlay {

        /**
         * 构造函数
         *
         * @param baiduMap 该 PoiOverlay 引用的 BaiduMap 对象
         */
        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int index) {
            super.onPoiClick(index);
            PoiInfo poi = getPoiResult().getAllPoi().get(index);
            // if (poi.hasCaterDetails) {
            mPoiSearch.searchPoiDetail((new PoiDetailSearchOption())
                    .poiUid(poi.uid));
            // }
            return true;
        }
    }

    /**
     * 画出附近区域的图形
     * @param center
     * @param radius
     */
    private void showNearbyArea(LatLng center, int radius) {
        OverlayOptions ooCircle = new CircleOptions().fillColor(0x200099ff)
                .center(center).stroke(new Stroke(5, 0x0099ff))
                .radius(radius);
        baiduMap.addOverlay(ooCircle);
    }
    /**
     * 弹出的popupwindow
     */
    private void initPop() {
        Log.i("TAG", "SADSAD");
        //构造一个popupwindow
        View view = LayoutInflater.from(context).inflate(R.layout.item_pop, null, false);
        final PopupWindow popupWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT, 400, true);

        popupWindow.setAnimationStyle(R.anim.anim_popshow);//加载动画
        popupWindow.setTouchable(true);
        //点击别处使pop消失
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return false;
            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setAnimationStyle(R.style.popwin_anim_style);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0Xffffff));//加背景才会显示
        popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 220);//设置位置
        tv_popname = (TextView) view.findViewById(R.id.tv_popname);
        tv_popaddress = (TextView) view.findViewById(R.id.tv_popaddress);
        tv_popnum = (TextView) view.findViewById(R.id.tv_popnum);
        tv_popkm = (TextView) view.findViewById(R.id.tv_popkm);
        iv_pop = (ImageView) view.findViewById(R.id.iv_pop);
    }
    /**
     * 算两点之间距离
     * @return
     */
    private double Distance(double longitude, double latitude, double long2, double lat2) {
        double a, b, R;
        R = 6371;// 地球半径    
        latitude = latitude * Math.PI / 180.0;
        lat2 = lat2 * Math.PI / 180.0;
        a = latitude - lat2;
        b = (longitude - long2) * Math.PI / 180.0;

        double d;
        double sa2, sb2;
        sb2 = Math.sin(b / 2.0);
        sa2 = Math.sin(a / 2.0);
        d = 2 * R * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(latitude)
                * Math.cos(lat2) * sb2 * sb2));
        return d*1000;
    }
}
